package com.lanqiao.companymanage.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lanqiao.companymanage.entity.User;
import com.lanqiao.companymanage.mapper.StaffSalaryMapper;
import com.lanqiao.companymanage.mapper.UserMapper;
import com.lanqiao.companymanage.service.StaffSalaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;

/**
 * @author 何小棍
 * 职工工资管理与添加
 */
@Service
public class StaffSalaryServiceImpl implements StaffSalaryService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    StaffSalaryMapper staffSalaryMapper;

    /**
     * 职工工资添加
     * @param user
     * @return
     */
    @Override
    public int addStaffSalary(User user) {
        // 计算工资
        calculateSalary(user);
        return staffSalaryMapper.addStaffSalary(user);
    }

    /**
     * 计算工资信息
     * @param user
     */
    private void calculateSalary(User user){
        //工资（合计 = 基本工资*工资系数+工资+职务+补贴）
        // 判断是否值,有才进行 BigDecimal 计算
        BigDecimal decimal = new BigDecimal("0");
        user = userMapper.selectUserByUserId(user.getUserId());
        if (!ObjectUtils.isEmpty(user.getSalary()) && !ObjectUtils.isEmpty(user.getDep().getSalarycount())){
            decimal = decimal.add(new BigDecimal(user.getSalary().toString()).multiply(new BigDecimal(user.getDep().getSalarycount().toString())));
        }
        if (!ObjectUtils.isEmpty(user.getGongning())){
            decimal = decimal.add(new BigDecimal(user.getGongning().toString()));
        }
        if (!ObjectUtils.isEmpty(user.getEmploy())){
            decimal = decimal.add(new BigDecimal(user.getEmploy().toString()));
        }
        if (!ObjectUtils.isEmpty(user.getButie())){
            decimal = decimal.add(new BigDecimal(user.getButie().toString()));
        }
        // 2位小数保留
        user.setSalarysum(decimal.setScale(2, RoundingMode.HALF_UP).doubleValue());
    }

    /**
     * 职工工资修改
     * @param user
     * @return
     */
    @Override
    public int updateStaffSalary(User user) {
        // 计算工资
        calculateSalary(user);
        return staffSalaryMapper.updateStaffSalary(user);
    }


    /**
     * 根据员工编号 userId查询
     * @param userId
     * @return
     */
    @Override
    public User selectByUserId(Integer userId) {
        return userMapper.selectUserByUserId(userId);
    }

    /**
     * 职工工资分页查询
     */
    @Override
    public IPage<User> listPage(Page<User> userPage) {
        return staffSalaryMapper.listPage(userPage);
    }


    /**
     * 根据员工编号(userId)id删除
     * @param userId
     * @return
     */
    @Override
    public int deletedByUserId(Integer userId) {
        return staffSalaryMapper.deletedByUserId(userId);
    }
}
